package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.redis.JobRedisKey;
import cn.wolfcode.web.fegin.SeckillProductFeignApi;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Setter
@Getter
@Component
public class SeckillProductCacheJob implements SimpleJob {
    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;
    @Value("${jobCron.initSeckillProduct}")
    private String cron;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void execute(ShardingContext shardingContext) {
        String time = shardingContext.getShardingParameter();
        dowork(time);
    }

    private void dowork(String time) {
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.queryByTimeForJob(Integer.parseInt(time));
        if (result==null||result.hasError()) {
            return;
        }
        List<SeckillProductVo> seckillProductVoList=result.getData();
        String seckillProductHashRealKey = JobRedisKey.SECKILL_PRODUCT_HASH.getRealKey(time);
        String seckillProductStockCountKey = JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time);
        redisTemplate.delete(seckillProductHashRealKey);
        redisTemplate.delete(seckillProductStockCountKey);
        for (SeckillProductVo vo : seckillProductVoList) {
            redisTemplate.opsForHash().put(seckillProductHashRealKey,String.valueOf(vo.getId()), JSON.toJSONString(vo));
             redisTemplate.opsForHash().put(seckillProductStockCountKey,String.valueOf(vo.getId()),String.valueOf(vo.getStockCount()));
        }
        System.out.println("同步完成");
    }

}
